from django import forms
from django.forms import Form
from django.contrib.auth.forms import UserCreationForm
from django.utils.translation import gettext_lazy as _
from django.contrib.auth import get_user_model
# from .models import User
from captcha.fields import CaptchaField


class UserCache(Form):
    user_cache = None
    password = forms.CharField(label=_('密码'), widget=forms.PasswordInput)

    # 设置clean_password之后，提示方式不同
    # def clean_password(self):
    #     print('1: ', self.user_cache)
    #     password = self.cleaned_data['password']
    #     if not self.user_cache:
    #         return password
    #     # if self.user_cache.password != password:
    #     if not self.user_cache.check_password(password):
    #         raise forms.ValidationError(_('You entered an invalid password.'))
    #     return password


class LoginViaUsernameForm(UserCache):
    username = forms.CharField(label=_('用户名'), )
    captcha = CaptchaField(label='验证码')
    User = get_user_model()
    field_order = ['username', 'password']

    # @property       # 只读属性
    # def field_order(self):
    #     return ['username', 'password']

    # def clean_username(self):
    #     username = self.cleaned_data['username']
    #     user = self.User.objects.filter(username=username).first()
    #     print('0: ', user)
    #     if not user:
    #         raise forms.ValidationError(_('You entered an invalid username.'))
    #
    #     self.user_cache = user
    #     return username


class LogInViaEmailForm(UserCache):
    email = forms.EmailField(label=_('电子邮箱'), )
    captcha = CaptchaField(label='验证码')
    User = get_user_model()

    field_order = ['email', 'password']

    def clean_email(self):
        email = self.cleaned_data['email']
        user = self.User.objects.filter(email=email)

        if not user:
            raise forms.ValidationError(_('You entered an invalid email address.'))

        self.user_cache = user
        return email


class RegisterForm(UserCreationForm):
    # 类UserCreationForm中已有username，password1和password2
    email = forms.EmailField(label=_('电子邮箱'), help_text=_('Required. Enter an existing email address.'))

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'password1', 'password2']

    def clean_email(self):
        print('0')
        email = self.cleaned_data['email']
        user = get_user_model().objects.filter(email=email).exists()
        if user:
            raise forms.ValidationError(_('该电子邮箱已存在，请重新输入'))
        return email

    # def save(self, commit=True):
    #     user = super().save(commit=False)
    #     user.set_password(self.cleaned_data["password1"])
    #     if commit:
    #         user.save()
    #     return user
